package com.dotflat.pay.controller;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;

import com.dotflat.utils.RemoteCallUtilAddon;
import com.starinside.wp.domain.WxUser;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.utils.RemoteCallUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.starinside.wp.foundation.constant.RequestConstant.TICKET;

@Slf4j
@RestController
@RequestMapping("/v2/pay/order")
@Api(tags = "缴费 - 待支付账单")
public class PayOrderController {

    @Value("${server.crm.url}")
    private String crmServerURL;

    @Autowired
    private BindedBabyService bindedBabyService;

    @ApiOperation(value = "获取账单列表")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "payStatus", value = "支付状态0:未付款; 1:已付款, 2:支付中", dataType = "int")
    })
    public StatusResponse getList(HttpServletRequest req,
                                  @RequestHeader(TICKET) String ticket,
                                  Integer payStatus){

        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        List<BindedBabyVO> children = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());
        List<String> clienteleIds = children.stream().map(BindedBabyVO::getCrmClienteleId).collect(Collectors.toList());

        Map p = new HashMap<>();

        p.put("clienteleIds", JSON.toJSONString(clienteleIds));
        if (payStatus != null){
            p.put("payStatus",payStatus.toString());
        }

        HashMap response = RemoteCallUtilAddon.getObject(crmServerURL + "/api/other_system/pay/order/list", p, null, HashMap.class, "获取订单失败");

        String code = (String) response.get("code");
        String msg = (String) response.get("msg");

        if (!ErrorCode.SUCCESSFUL.equals(code)){
            throw new BusinessException(code, "获取订单失败:" + msg);
        }

        List result = (List) response.get("data");
        if (result == null){
            result = new ArrayList<>();
        }

        return StatusResponse.success(result);
    }

    @ApiOperation(value = "获取一个账单详情")
    @GetMapping()
    public StatusResponse get(HttpServletRequest req,
                              @RequestHeader(TICKET) String ticket,
                              String id){
        WxUser loginUser = (WxUser) req.getSession().getAttribute("loginUser");

        Map p = new HashMap<>();
        p.put("id", id);

        HashMap response = RemoteCallUtilAddon.getObject(crmServerURL + "/api/other_system/pay/order", p, null, HashMap.class, "获取订单失败");

        String code = (String) response.get("code");
        String msg = (String) response.get("msg");

        if (!ErrorCode.SUCCESSFUL.equals(code)){
            throw new BusinessException(code, "获取订单失败:" + msg);
        }

        Map result = (Map) response.get("data");
        if (result != null){
            List<BindedBabyVO> children = bindedBabyService.getAllBindedBabyByParent(loginUser.getParentId());
            List<String> clienteleIds = children.stream().map(BindedBabyVO::getCrmClienteleId).collect(Collectors.toList());

            String clienteleId = (String) result.get("clienteleId");
            if (clienteleIds.contains(clienteleId)){
                return StatusResponse.success(result);
            }
        }

        return StatusResponse.error(ErrorCode.MATERIAL_NOT_EXIST, "没有对应订单");
    }

}
